package cn.server;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.Socket;

public class SendMessage extends Thread {
	private Socket socket = null;

	public SendMessage(Socket soc) {
		this.socket = soc;
	}

	public void run() {
		String message = null;
		String cmd = null;
		BufferedReader reader = null;
		StringBuffer msg = new StringBuffer();
		try {
			reader = new BufferedReader(new InputStreamReader(socket
					.getInputStream(), "utf8"));
			while (null != (message = reader.readLine())) {
				msg.append(message + "\n");
			}
			message = msg.toString();
			cmd = message.substring(0, 4);// get command
			message = message.substring(4);

			switch (Integer.parseInt(cmd)) {
			case 1:// send to friend
				sendToClient(message);
				break;
			default:
				break;
			}

		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				if (null != reader) {
					reader.close();
				}
				if (null != socket) {
					socket.close();
				}
			} catch (IOException ie) {
				ie.printStackTrace();
			}
		}
	}

	private void sendToClient(String msg) {
		String toMid = msg.substring(0, 7);
		Socket toSocket = new Socket();
		PrintWriter writer = null;
		try {
			if (null != (toSocket = DAServerSocket.userHash.get(toMid))) {
				writer = new PrintWriter(toSocket.getOutputStream());
				writer.write(msg);
				writer.flush();
			} else {
				// save message to database
			}
		} catch (IOException ioe) {
			ioe.printStackTrace();
		} finally {
			if (writer != null)
				writer.close();
			if (toSocket != null)
				toSocket = null;
		}
	}
}
